type state = Init | Zero | Nonzero of int

(** might throw [End_of_file] exception *)
let rec step (s : state) (c : char) =
  match s with
  | Init -> (
      match c with
      | '0' -> step Zero (input_char stdin)
      | it when it >= '1' && it <= '9' ->
          step (Nonzero (int_of_char it - int_of_char '0')) (input_char stdin)
      | _ -> step Init (input_char stdin))
  | Zero -> if c == '%' then print_int 0 else step Init c
  | Nonzero value -> (
      match c with
      | '%' -> print_int value
      | it when it >= '0' && it <= '9' ->
          step
            (Nonzero (value * 10 + (int_of_char it - int_of_char '0')))
            (input_char stdin)
      | _ -> step Init (input_char stdin))

let () = try step Init (input_char stdin) with End_of_file -> exit 1
